"""
Copyright (c) 2017 Dependable Systems Laboratory, EPFL

Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:

The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software.

THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
SOFTWARE.
"""


import glob
import json
import logging
import os


logger = logging.getLogger('coverage')


def get_tb_files(results_dir):
    """
    Gets a list of translation block coverage files generated by S2E's
    TranslationBlockCoverage plugin.

    Args:
        results_dir: Path to an ``s2e-out-*`` directory in an analysis project.

    Returns:
        A list of translation block coverage files
    """
    # Include both multi-node and single node results
    tb_coverage_files = glob.glob(os.path.join(results_dir, '*', 'tbcoverage-*.json')) + \
                        glob.glob(os.path.join(results_dir, 'tbcoverage-*.json'))
    if not tb_coverage_files:
        logger.warning('No translation block coverage files found in s2e-last. '
                       'Did you enable the ``TranslationBlockCoverage`` '
                       'plugin in s2e-config.lua?')

    return tb_coverage_files


def parse_tb_file(path, module):
    """
    Parse a translation block coverage file generated by S2E's
    ``TranslationBlockCoverage`` plugin.
    """
    with open(path, 'r') as f:
        try:
            tb_coverage_data = json.load(f)
        except Exception:
            logger.warning('Failed to parse translation block JSON file %s',
                           path)
            return None

    if not tb_coverage_data:
        logger.warning('Translation block JSON file %s is empty', path)
        return None

    if module not in tb_coverage_data:
        logger.warning('Target %s not found in translation block JSON file %s',
                       module, path)
        return None

    return tb_coverage_data[module]
